import React, { useEffect, useReducer, useRef } from "react";

/*
 * @Author: cyfqyb
 * @Date: 2023-10-25 17:18:42
 * @LastEditors: cyfqyb cy15770703229@163.com
 * @LastEditTime: 2023-10-27 01:34:23
 * @FilePath: \ImBackend\src\view\Data.tsx
 * @Description: 数据页面
 */
export default function Data() {
	return (
		<>
			<DataTest />
			<DataTest2 />
		</>
	);
}

const DataTest: React.FC<{}> = () => {
	let [num, setNum] = React.useState(0);
	const Reducer = (state: number, action: { name: "add" | "del" | "reset"; payload?: number }) => {
		const { name, payload } = action;
		switch (name) {
			case "add":
				return state + 1;
			case "del":
				return state - 1;
			case "reset":
				return payload == undefined ? 0 : payload;
		}
	};
	const [num2, dispatch] = useReducer(Reducer, 0);
	const n1 = useRef(null);
	return (
		<>
			<div
				ref={n1}
				onClick={() => {
					setNum(++num);
				}}
				className="bg-sky w100 h50 mlr-a line-height-50 text-center cursor-pointer"
			>
				{num + "****" + num2}
				<button
					onClick={() => {
						dispatch({ name: "add" });
					}}
				>
					num2
				</button>
			</div>
		</>
	);
};

const DataTest2: React.FC<{}> = () => {
	let [num, setNum] = React.useState(0);
	const handle = () => {
		setNum(num + 1);
	};
	useEffect(() => {
		return () => {
			//获取的是上一次组件的状态,
			console.log(`返回的函数会在组件释放的时候执行:${num}`);
		};
	}, [num]);
	return (
		<div>
			<h2 onClick={handle}>{num}</h2>
		</div>
	);
};
